﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Epic.TakeHome.Al {
  class FileManager {
    private FileInfo _file;
    private Char[]  _productSeperator =  {'\u0007'} ;
    private Char[] _dataSeperator =  {'\u0005'} ;
    
    public FileManager(FileInfo file) {
      _file = file;
    }

    public void Load(InvSystem system) {
      String[] products = { };
      CheckFile();
      StreamReader sr = new StreamReader(_file.OpenRead());
      for (String str = sr.ReadLine(); str != null; str = sr.ReadLine()) {
        products = str.Split(_productSeperator );
      }
      String[] datas;
      foreach (String product in products) {
        datas = product.Split(_dataSeperator);
        if (datas.Length < 4) continue;
        system.addProduct(datas[0],Convert.ToDouble(datas[1]), Convert.ToDouble(datas[2]), Convert.ToInt16 (datas[3]));
      }
      sr.Close();
    }

    public void SaveTo(InvSystem system) {
      if (_file.Exists) {
        _file.Delete();
      }
      CheckFile();
      StreamWriter sw = new StreamWriter(File.OpenWrite(_file.FullName));
      for (int i=0; i<system.products().Count(); i++) {
        Product p = system.products()[i];
        sw.Write(p.Name + _dataSeperator[0]);
        sw.Write(p.Weight.ToString ()  + _dataSeperator[0] );
        sw.Write(p.WholeSalePrice.ToString() + _dataSeperator[0]);
        sw.Write(p.Quantity.ToString() + _dataSeperator[0]);
        sw.Write(_productSeperator[0]);
      }
      sw.Close();
    }

    private void CheckFile() {
      if (!_file.Exists) {
        _file.Create();
      }
    }
  }
}
